<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input v-model.trim="name" type="text" />
    </div>
    <div>
      <span>年龄:</span>
      <input v-model.number="age" type="number" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="x">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.x }}</td>
          <td>
            <button @click="odd(index)">删除</button>
            <button @click="bianji(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [
        {
          name: "tom",
          age: 18,
          x: "男",
        },
        {
          name: "zkx",
          age: 20,
          x: "男",
        },
      ],
      name: "",
      age: 0,
      x: "",
      is: false,
      nm: 0,
    };
  },
  methods: {
    add() {
      if (
        this.name.length == 0 ||
        this.age < 0 ||
        this.age.length == 0 ||
        this.x.length == 0
      ) {
        return alert("请输入正确的个人信息");
      } else if (this.is == true) {
        this.is = false;
        this.list.splice(this.nm, 1, {
          name: this.name,
          age: this.age,
          x: this.x,
        });
        this.name = "";
        (this.age = 0), (this.x = "");
        return;
      } else if (this.nm == false) {
        this.list.push({
          name: this.name,
          age: this.age,
          x: this.x,
        });
      }

      (this.name = ""), (this.age = 0), (this.x = "");
    },
    odd(val) {
      this.list.splice(val, 1);
    },
    bianji(val) {
      this.name = this.list[val].name;
      this.age = this.list[val].age;
      this.x = this.list[val].x;
      this.is = true;
      this.nm = val;
    },
  },
};
</script>
